package org.xu.service.impl;

import com.core.base.Reply;
import com.core.redis.RedisLock;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.xu.dao.WorkFlowLogEntityExtMapper;
import org.xu.dto.WorkFlowLogDTO;
import org.xu.entity.WorkFlowLogEntity;
import org.xu.request.WorkLogRequest;
import org.xu.request.WorkPageRequest;
import org.xu.service.WorkFlowLogService;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
public class WorkFlowLogServiceImpl implements WorkFlowLogService {
    @Resource
    private WorkFlowLogEntityExtMapper mapper;

    @Override
    public List<WorkFlowLogEntity> list() {
        return mapper.selectAll();
    }

    @Override
    public Reply<List<WorkFlowLogEntity>> lockGet() {
        try(RedisLock redisLock = RedisLock.tryLock("org:test:lockGet",0,5, TimeUnit.SECONDS)) {
            if (!redisLock.isLockSuccess()){
                return Reply.failure("获取锁失败");
            }
            Thread.sleep(2000);
            return Reply.success(mapper.selectAll());
        }catch (Exception e){
            log.error("lockGet:",e);
        }
        return Reply.failure("获取数据失败");
    }

    @Override
    public List<WorkFlowLogDTO> query(WorkLogRequest request) {
        log.info("========== 查询参数：{}",request);
        List<WorkFlowLogEntity> list = mapper.getByParams(request);
        List<WorkFlowLogDTO> list2 = list.stream().map(t -> {
            WorkFlowLogDTO dto = new WorkFlowLogDTO();
            BeanUtils.copyProperties(t, dto);
            return dto;
        }).collect(Collectors.toList());
        System.out.println(list2);
        return list2;
    }

    @Override
    public PageInfo<WorkFlowLogDTO> pageQuery(WorkPageRequest request) {
        PageHelper.startPage(request.getIndex(),request.getPageSize());
        List<WorkFlowLogEntity> list = mapper.pageQuery(request);
        List<WorkFlowLogDTO> list2 = list.stream().map(t -> {
            WorkFlowLogDTO dto = new WorkFlowLogDTO();
            BeanUtils.copyProperties(t, dto);
            dto.setOperationTime(t.getCreateTime());
            return dto;
        }).collect(Collectors.toList());
        return new PageInfo<>(list2);
    }

    @Override
    public int insert(WorkFlowLogEntity record) {
        return mapper.insert(record);
    }

    @Override
    public List<WorkFlowLogEntity> listByDataId(String dataId) {
        return mapper.listByDataId(dataId);
    }

    @Override
    public void deleteHistoryData(LocalDate oldLocalDate) {
        mapper.deleteHistoryData(oldLocalDate);
    }
}
